<template>
  <el-input
    ref="pwdInput"
    v-model="passwordValue"
    :class="defineClass"
    clearable
    :autofocus="autofocus"
    type="text"
    size="large"
    :placeholder="placeholder"
    auto-complete="new-password"
    @compositionend.native="compositionend"
    @compositionstart.native="compositionstart"
    @input.native="inputVal"
    @keyup.enter.native="makeSure"
  >
    <template #suffix>
      <i class="iconfont c-fs-14 cursor-pointer" @click="clickShow">&#xe694;</i>
    </template>
  </el-input>
</template>

<script setup lang="ts">
// 定义接收的 props
const props = defineProps({
  // 提示信息
  placeholder: {
    type: String,
    default: "",
  },
  // 自定义样式
  defineClass: {
    type: String,
    default: "",
  },
  // 是否自动聚焦
  autofocus: {
    type: Boolean,
    default: true,
  },
});
// 密码
const passwordValue = ref<string>("");
// 替换密码
const pwd = ref<string>("");
// 是否输入中文
const chineseStatus = ref<boolean>(false);
// 定义 emits
const emit = defineEmits(["clickShow", "makeSure", "changeValue"]);

// 向父组件传递值
const makeSure = () => {
  emit("makeSure");
};
// 点击展示传递值
const clickShow = () => {
  emit("clickShow");
};

// 修改替换密码
const replacePwd = (newVal: string) => {
  if (pwd.value === "" && newVal && newVal.indexOf("●") === -1) {
    pwd.value = newVal;
  }
  if (pwd.value.trim().length != newVal.trim().length) {
    let data = newVal.split("");
    let count = 0;
    for (let i = 0; i < data.length; i++) {
      if (data[i] == "●") {
        data[i] = pwd.value[i - count]; // 防止突然前面增加输入，然后导致不会变圆点
      } else {
        count += 1;
      }
    }
    newVal = data.join("");
    pwd.value = newVal;
  }
  let str = "";
  for (let j = 0; j < newVal.length; j++) {
    str += "●";
  }
  passwordValue.value = str;
  emit("changeValue", pwd.value);
};
// 中文输入法输入结束执行事件
const compositionend = () => {
  chineseStatus.value = false;
  replacePwd(passwordValue.value);
};
// 中文输入法开始输入执行事件
const compositionstart = () => {
  chineseStatus.value = true;
  replacePwd(pwd.value);
};
// 英文输入法执行事件
const inputVal = () => {
  if (!chineseStatus.value) {
    replacePwd(passwordValue.value);
  }
};
// 暴露方法给父组件
defineExpose({
  replacePwd,
});
</script>

<style scoped lang="scss"></style>
